import React, { Component } from 'react'
import { Button, Card, Select, Input, Table, message } from 'antd';
import {connect} from "react-redux"
import { PlusCircleOutlined, SearchOutlined } from '@ant-design/icons';
import { reqProductList, reqUpdataProdStatus, reqSearchProdList } from "../../api/index"
import { PAGE_SIZE } from "../../config/index"
import {createSaveProdAction} from "../../redux/actions/product_action"
const { Option } = Select;



class Product extends Component {
    state = {
        productList: [],  //商品列表数据(分页)
        total: "",          //一共有几页
        currentPageNum: 1,   //当前在哪一页
        keyWord: '',
        searchType: 'productName'
    }
    //获取商品分页列表
    getProductList = async (number = 1) => {
        let result
        if (this.isSearch) {
            const { searchType, keyWord } = this.state
            result = await reqSearchProdList(number , PAGE_SIZE, searchType, keyWord)
        } else {
            result = await reqProductList(number, PAGE_SIZE)
        }
        const { status, data } = result
        //将获取到的商品信息存入redux ----->  到时候给<详情>用
        this.props.saveProduct(data.list)
        if (status === 0) {
            this.setState({
                productList: data.list,
                total: data.total,
                currentPageNum: data.pageNum
            })
        }
        else message.error('获取商品列表失败')
    }
    componentDidMount() {
        this.getProductList()
    }
    //更新商品状态
    updataProdStatus = async ({ _id, status }) => {
        if (status === 1) status = 2
        else status = 1
        let result = await reqUpdataProdStatus(_id, status)
        if (result.status === 0) {
            message.success('更新商品状态成功')
            //如果数据很多，就遍历找到该项更改状态   ------>  不要调用getProductList
            let productList = this.state.productList.map((item) => {
                if (item._id === _id) {
                    item.status = status
                    return item
                }
                return item
            })
            this.setState({ productList })
        }
        else message.error('更新商品状态失败')
    }
    //搜索
    search = async () => {
        this.isSearch = true
        this.getProductList()
    }

    render() {
        const dataSource = this.state.productList

        const columns = [
            {
                title: '商品名称',
                dataIndex: 'name',
                key: 'name',
                width: '18%'
            },
            {
                title: '商品描述',
                dataIndex: 'desc',
                key: 'desc',
            },
            {
                title: '价格',
                dataIndex: 'price',
                key: 'price',
                render: (price) => { return "￥" + price },
                align: 'center',
                width: '9%'
            },
            {
                title: '状态',
                // dataIndex: 'status'  【严重注意】：不写，则是把这一整项(里面包括：status、id等)拿过来了
                key: 'status',
                render: (item) => {
                    return (
                        <>
                            <Button
                                type={item.status === 1 ? "danger" : "primary"}
                                onClick={() => { this.updataProdStatus(item) }}
                            >
                                {item.status === 1 ? "下架" : "上架"}</Button><br />
                            <span>{item.status === 1 ? "在售" : "已停售"}</span>
                        </>
                    )
                },
                align: 'center',
                width: '10%'
            },
            {
                title: '操作',
                // dataIndex: 'operation',
                key: 'operation',
                render: (item) => {
                    return (
                        <>
                            <Button type='link' onClick={()=>{this.props.history.push(`/admin/prod_about/product/detail/${item._id}`)}}>详情</Button><br />
                            <Button type='link' onClick={()=>{this.props.history.push(`/admin/prod_about/product/add_update/${item._id}`)}}>修改</Button>
                        </>
                    )
                },
                align: 'center',
                width: '10%'
            }
        ];
        return (
            <Card
                title={
                    <>
                        <Select
                            defaultValue="productName"
                            style={{ width: 120 }}
                            onChange={(value) => { this.setState({ searchType: value }) }}   //antD中select的onChange事件直接传的value值	
                        >
                            <Option value="productName">按名称搜索</Option>
                            <Option value="productDesc">按描述搜索</Option>
                        </Select>
                        <Input
                            placeholder="请输入搜索关键字"
                            style={{ width: "15%", margin: "0 10px" }}
                            onChange={(event) => { this.setState({ keyWord: event.target.value }) }}  //antD中input的onChange事件直接传的event事件源
                        />
                        <Button type="primary" onClick={this.search}><SearchOutlined />搜索</Button>
                    </>
                }
                extra={<Button type='primary' onClick={()=>{this.props.history.push('/admin/prod_about/product/add_update')}}><PlusCircleOutlined />添加商品</Button>}
            >
                <Table
                    bordered rowKey="_id"
                    dataSource={dataSource}
                    columns={columns}
                    pagination={{
                        total: this.state.total,
                        current: this.state.currentNum,
                        pageSize: PAGE_SIZE,
                        onChange: this.getProductList    //pagination里的onChange事件的回调(a)=>{ } 参数a就是当前在第几页
                    }}
                />
            </Card>
        )
    }
}

export default  connect(
    state => ({}),
    {saveProduct:createSaveProdAction}
)(Product)